from dataclasses import dataclass
from typing import Any, Optional

from .speaker_info import SpeakerInfoData


@dataclass
class SpeechRecognitionData:
    """语音识别响应数据模型

    包含语音识别的文本、说话人信息、置信度等数据
    """

    message_id: str
    timestamp: int
    mode: str
    status: str
    session_id: str = ""
    text: str = ""
    start_time: Optional[int] = None
    end_time: Optional[int] = None
    duration: Optional[int] = None
    confidence: float = 0.0
    speaker_info: Optional[SpeakerInfoData] = None

    def __post_init__(self):
        # 如果传入的是字典，则转换为 SpeakerInfoData 对象
        if isinstance(self.speaker_info, dict):
            self.speaker_info = SpeakerInfoData.from_dict(self.speaker_info)

    def to_dict(self) -> dict[str, Any]:
        """转换为字典格式，便于序列化"""
        result: dict[str, Any] = {
            "message_id": self.message_id,
            "timestamp": self.timestamp,
            "mode": self.mode,
            "status": self.status,
            "session_id": self.session_id,
            "text": self.text,
            "start_time": self.start_time,
            "end_time": self.end_time,
            "duration": self.duration,
            "confidence": self.confidence,
        }

        # 如果有说话人信息，转换为字典
        if self.speaker_info:
            result["speaker_info"] = self.speaker_info.to_dict()
        else:
            result["speaker_info"] = None

        return result
